//************************************************************
//
// REGSTEP 9.  REACTION FUNCTION WITH MEDIAN FIRM over the BS space
//
// AUTHOR: LIONEL NESTA
//
// DATASOURCE: USING final_reaction_functions.dta FROM DATASTEP 5
//
//*************************************************************


// PREAMBLE
*set processors 24

clear
clear matrix 
clear mata
set more off
set mem 600m
set matsize 800

pwd

cd ..\DATA

// OPENING FILE

use final_reaction_functions.dta, clear

drop if year < 1990

* Building instruments

egen mrd_sec1 = mean(lnrd1), by(sector1 year)
egen mrd_sec2 = mean(lnrd2), by(sector2 year)

gen mrd_sec1_fs = mrd_sec1 - lnrd1
gen mrd_sec2_fs = mrd_sec2 - lnrd2

set more off

mat RES = J(20,5,.)

// CHOICE OF CORRELATION VS COSINE

egen double cos_tek_5  = cut(c_techno_c), at(-1,-.6,-.2,.2,.6,1)
egen double cos_mak_5  = cut(c_market_c), at(-1,-.6,-.2,.2,.6,1)

replace cos_tek_5 = 1 if cos_tek_5 == -1
replace cos_tek_5 = 2 if cos_tek_5 == -.6
replace cos_tek_5 = 3 if cos_tek_5 == -.2
replace cos_tek_5 = 4 if cos_tek_5 == .2
replace cos_tek_5 = 5 if cos_tek_5 == .6

replace cos_mak_5 = 1 if cos_mak_5 == -1
replace cos_mak_5 = 2 if cos_mak_5 == -.6
replace cos_mak_5 = 3 if cos_mak_5 == -.2
replace cos_mak_5 = 4 if cos_mak_5 == .2
replace cos_mak_5 = 5 if cos_mak_5 == .6

cd ..\RESULTS

forvalues col = 1/5 {
	preserve
		drop if cos_tek_5 != `col'

		collapse (mean) lnrd1 lnrd2 lnrdi1 lnrdi2  c_techno_c c_market_c lnk1 lnliq_ratio1 msh1 msh12 lnrdpatsm1 L1lnrdpatsm1 psm_lnrd1 L1lnrd2 mrd_sec2 ///
		 lnk2 lnliq_ratio2 msh2 lnrdpatsm2 L1lnrd1   L1lnk1 L1lnliq_ratio1 L1msh1 L2lnrdpatsm1 L2lnrdpatsm2, by(gvkey1 year cos_mak_5)

		tab year, gen(year_)
		egen fcid  = group(gvkey1 cos_mak_5)
		drop if fcid==.
		tsset fcid year

		local line = 1

			forvalues  case = 5(-1)1 {
				quietly {
					reg  lnrd1 lnk1 lnrd2 lnliq_ratio1 L1lnrdpatsm1 psm_lnrd1 year_*  if cos_mak_5 == `case'
				}
				local linac = `line' 
				mat RES[`linac', `col'] = _b[lnrd2] 
				local linac = `linac' + 1
				mat V = e(V)
				local se =  V[1,1]^(1/2)
				mat RES[`linac', `col'] =  `se'				
				local linac = `linac' + 1
				
				local beta = _b[lnrd2]
				local z = abs(`beta' / `se')
				mat RES[`linac', `col'] = 1 - normal(`z') 
				
				local line = `line' + 4	
			
			}
		
	restore

}
	



clear

svmat RES, names(tek)


local listpct "mak5 mak4 mak3 mak2 mak1" 
local line = 1
gen Case_Type = ""
foreach p of local listpct {
	replace Case_Type = "`p'" in `line'
	local line = `line' + 4
} 


forvalues x = 1(1)5{
	format tek`x' %12.3f
} 
	
order  Case_Type

dataout , save(table4_test)  dec(3) word tex excel replace
